<template>
  <div class="container">
    <h2 class="title">个人所得税专项附加扣除智能筹划系统</h2>
    <div class="tip" style="margin-bottom:12px;">* 所有金额单位均为“元/年”</div>
    <section class="card">
      <h3 style="display:flex;align-items:center;gap:12px;">
        一、家庭成员信息
        <button @click="generateTestMembers" class="btn btn-primary" style="padding:4px 12px;font-size:13px;">一键测试</button>
      </h3>
      <!-- PC端表格 -->
      <div class="table-responsive member-table-pc">
        <table class="table">
          <colgroup>
            <col style="width: 80px;">
            <col style="width: 100px;">
            <col style="width: 100px;">
            <col style="width: 100px;">
            <col style="width: 100px;">
            <col style="width: 100px;">
            <col style="width: 100px;">
            <col style="width: 80px;">
          </colgroup>
          <thead>
            <tr>
              <th>姓名<span class="required">*</span></th>
              <th>关系<span class="required">*</span></th>
              <th>工资收入<span class="required">*</span></th>
              <th>劳务报酬</th>
              <th>特许权使用费</th>
              <th>稿酬</th>
              <th>个人承担的五险一金</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(m,idx) in members" :key="idx">
              <td>
                <input v-model="m.name" placeholder="姓名" class="input name-input" 
                  :class="{'input-error': m.error}" />
                <div v-if="m.error && !m.name.trim()" class="error-tip">姓名为必填项</div>
              </td>
              <td>
                <select v-model="m.relation" class="input relation-select"
                  :class="{'input-error': m.error}">
                  <option value="">请选择</option>
                  <option v-for="opt in getRelationOptions(idx)" :key="opt.value" :value="opt.value">{{opt.label}}</option>
                </select>
                <div v-if="m.error && !m.relation.trim()" class="error-tip">关系为必填项</div>
              </td>
              <td>
                <div class="input-unit-group">
                  <input v-model.number="m.salary" type="number" min="0" class="input short" placeholder=""
                    :class="{'input-error': m.error}" />
                  <span class="input-unit">元/年</span>
                </div>
                <div v-if="m.error && (m.salary === '' || isNaN(m.salary))" class="error-tip">工资为必填项</div>
              </td>
              <td>
                <div class="input-unit-group">
                  <input v-model.number="m.labor" type="number" min="0" class="input short" placeholder="" />
                  <span class="input-unit">元/年</span>
                </div>
              </td>
              <td>
                <div class="input-unit-group">
                  <input v-model.number="m.copyright" type="number" min="0" class="input short" placeholder="" />
                  <span class="input-unit">元/年</span>
                </div>
              </td>
              <td>
                <div class="input-unit-group">
                  <input v-model.number="m.manuscript" type="number" min="0" class="input short" placeholder="" />
                  <span class="input-unit">元/年</span>
                </div>
              </td>
              <td>
                <div class="input-unit-group">
                  <input v-model.number="m.insurance" type="number" min="0" class="input short" placeholder="" />
                  <span class="input-unit">元/年</span>
                </div>
              </td>
              <td>
                <button @click="confirmRemoveMember(idx)" v-if="members.length>1" class="btn btn-danger">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 移动端卡片 -->
      <div class="member-cards-mobile">
        <div class="member-card" v-for="(m, idx) in members" :key="idx">
          <div class="row row-pair">
            <div class="row-item">
              <label>姓名<span class="required">*</span></label>
              <input v-model="m.name" placeholder="姓名" class="input" 
                :class="{'input-error': m.error}" />
              <div v-if="m.error && !m.name.trim()" class="error-tip">姓名为必填项</div>
            </div>
            <div class="row-item">
              <label>关系<span class="required">*</span></label>
              <select v-model="m.relation" class="input short"
                :class="{'input-error': m.error}">
                <option value="">请选择</option>
                <option v-for="opt in getRelationOptions(idx)" :key="opt.value" :value="opt.value">{{opt.label}}</option>
              </select>
              <div v-if="m.error && !m.relation.trim()" class="error-tip">关系为必填项</div>
            </div>
          </div>
          <div class="row row-pair">
            <div class="row-item">
              <label>工资收入<span class="required">*</span></label>
              <div class="input-unit-group">
                <input v-model.number="m.salary" type="number" min="0" class="input" 
                  :class="{'input-error': m.error}" />
                <span class="input-unit">元/年</span>
              </div>
              <div v-if="m.error && (m.salary === '' || isNaN(m.salary))" class="error-tip">工资为必填项</div>
            </div>
            <div class="row-item">
              <label>劳务报酬</label>
              <div class="input-unit-group">
                <input v-model.number="m.labor" type="number" min="0" class="input" />
                <span class="input-unit">元/年</span>
              </div>
            </div>
          </div>
          <div class="row row-pair">
            <div class="row-item">
              <label>特许权使用费</label>
              <div class="input-unit-group">
                <input v-model.number="m.copyright" type="number" min="0" class="input" />
                <span class="input-unit">元/年</span>
              </div>
            </div>
            <div class="row-item">
              <label>稿酬</label>
              <div class="input-unit-group">
                <input v-model.number="m.manuscript" type="number" min="0" class="input" />
                <span class="input-unit">元/年</span>
              </div>
            </div>
          </div>
          <div class="row row-full">
            <label>个人承担的五险一金</label>
            <div class="input-unit-group">
              <input v-model.number="m.insurance" type="number" min="0" class="input" />
              <span class="input-unit">元/年</span>
            </div>
          </div>
          <div class="row row-full">
            <button @click="confirmRemoveMember(idx)" v-if="members.length>1" class="btn btn-danger">删除</button>
          </div>
        </div>
      </div>
      <button @click="addMember" class="btn btn-primary">添加成员</button>
    </section>
    <section class="card">
      <h3>二、专项附加扣除信息（全家总额，选择由谁扣除）</h3>
      <div class="deduction-list">
        <!-- 子女教育/婴幼儿照护费支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(child, idx) in deductionInfo.child" :key="'child'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addChild" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeChild(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              子女教育/婴幼儿照护费
            </span>
            <div class="input-unit-group">
              <input v-model.number="child.amount" type="number" min="0" class="input short" :max="24000" @input="checkChildLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="child.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in childAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 住房贷款利息支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(loan, idx) in deductionInfo.loan" :key="'loan'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addLoan" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeLoan(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              住房贷款利息
            </span>
            <div class="input-unit-group">
              <input v-model.number="loan.amount" type="number" min="0" class="input short" :max="12000" @input="checkLoanLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="loan.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in loanAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 住房租金支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(rent, idx) in deductionInfo.rent" :key="'rent'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addRent" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeRent(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              住房租金
            </span>
            <div class="input-unit-group rent-group" style="position:relative;display:inline-block;">
              <select v-model.number="rent.amount" class="input short">
                <option value="">请选择</option>
                <option :value="18000">直辖市/省会/计划单列市：18000</option>
                <option :value="13200">户籍超100万城市：13200</option>
                <option :value="9600">户籍≤100万城市：9600</option>
              </select>
              <span class="input-unit">元/年</span>
              <span class="rent-tip">住房租金按城市规模</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="rent.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in rentAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 大病医疗支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(illness, idx) in deductionInfo.illness" :key="'illness'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addIllness" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeIllness(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              大病医疗
            </span>
            <div class="input-unit-group">
              <input v-model.number="illness.amount" type="number" min="0" class="input short" :max="65000" @input="checkIllnessLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="illness.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in illnessAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 赡养老人支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(elder, idx) in deductionInfo.elder" :key="'elder'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addElder" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeElder(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              赡养老人
            </span>
            <div class="input-unit-group">
              <input v-model.number="elder.amount" type="number" min="0" class="input short" :max="36000" @input="checkElderLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="elder.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in elderAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 学历继续教育支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(degree, idx) in deductionInfo.degree" :key="'degree'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addDegree" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeDegree(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              学历继续教育
            </span>
            <div class="input-unit-group">
              <input v-model.number="degree.amount" type="number" min="0" max="4800" class="input short" @input="checkDegreeLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="degree.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in degreeAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
        
        <!-- 职业资格继续教育支持多项 -->
        <transition-group name="deduction-item" tag="div" class="deduction-group">
          <div v-for="(education, idx) in deductionInfo.education" :key="'education'+idx" class="deduction-item">
            <span class="deduction-label">
              <template v-if="idx === 0">
                <button @click="addEducation" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #42b983; color:#42b983; background:#fff; cursor:pointer;">+</button>
              </template>
              <template v-else>
                <button @click="removeEducation(idx)" type="button" style="margin-right:6px; font-size:18px; width:24px; height:24px; line-height:20px; border-radius:50%; border:1px solid #ff4d4f; color:#ff4d4f; background:#fff; cursor:pointer;">-</button>
              </template>
              职业资格继续教育
            </span>
            <div class="input-unit-group">
              <input v-model.number="education.amount" type="number" min="0" max="3600" class="input short" @input="checkEducationLimit(idx)" />
              <span class="input-unit">元/年</span>
            </div>
            <span class="deduction-by">由</span>
            <select v-model="education.owner" class="input short">
              <option value="">请选择</option>
              <option v-for="name in educationAvailableOwners(idx)" :key="name" :value="name">{{name}}</option>
            </select>
            <span class="deduction-by">扣除</span>
          </div>
        </transition-group>
      </div>

      <div class="tip">* 住房贷款利息和住房租金只能选一项，系统自动取高者</div>
      <button @click="calcTax" class="btn btn-calc">计算税额</button>
    </section>
    <section class="card">
      <h3>三、计算结果</h3>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th>姓名</th>
              <th>年收入额</th>
              <th>个人承担的五险一金</th>
              <th>专项附加扣除</th>
              <th>其他扣除</th>
              <th>固定费用</th>
              <th>应纳税所得额</th>
              <th>适用税率</th>
              <th>速算扣除数</th>
              <th>应缴税额</th>
              <th>专项附加扣除明细</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="r in result" :key="r.name">
              <td>{{r.name}}</td>
              <td>{{r.income}}</td>
              <td>{{r.insurance}}</td>
              <td>{{r.deduction}}</td>
              <td>{{r.other}}</td>
              <td>{{r.fixed}}</td>
              <td>{{r.taxable}}</td>
              <td>{{r.rate}}</td>
              <td>{{r.quick}}</td>
              <td>{{r.tax}}</td>
              <td>
                <div v-for="item in Object.entries(r.deductions).filter(([k, v]) => v)" :key="item[0]">
                  {{deductionLabels[item[0]]}}: {{item[1]}}
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-if="result.length" class="total-tax">全家总税负：<b>{{totalTax}}</b> 元</div>
    </section>
  </div>
</template>

<script setup>

import { ref, computed } from 'vue'


// 家庭成员结构（新增error字段，标记校验状态）
const members = ref([
  {
    name: '',
    relation: '',
    salary: 0,
    labor: 0,
    copyright: 0,
    manuscript: 0,
    insurance: 0,
    error: false
  }
])

// 专项附加扣除信息及分配人
const deductionInfo = ref({
  child: [ { amount: 0, owner: '' } ], // 子女教育/婴幼儿照护费，支持多项
  loan: [ { amount: 0, owner: '' } ],  // 住房贷款利息，支持多项
  rent: [ { amount: '', owner: '' } ],  // 住房租金，支持多项
  illness: [ { amount: 0, owner: '' } ], // 大病医疗，支持多项
  elder: [ { amount: 0, owner: '' } ], // 赡养老人，支持多项
  education: [ { amount: 0, owner: '' } ], // 职业资格继续教育，支持多项
  qualification: { amount: 0, owner: '' }, // 保留字段
  degree: [ { amount: 0, owner: '' } ], // 学历继续教育，支持多项
})

const deductionLabels = {
  child: '子女教育/婴幼儿照护费',
  loan: '住房贷款利息',
  rent: '住房租金',
  illness: '大病医疗',
  elder: '赡养老人',
  education: '职业资格继续教育',
  degree: '学历继续教育',
  qualification: '职业资格继续教育'
}

// 其他扣除
const otherDeduction = ref(0)

// 结果
const result = ref([])
const totalTax = ref(0)

// 税率表
const taxTable = [
  { min: 0, max: 36000, rate: 0.03, quick: 0 },
  { min: 36000, max: 144000, rate: 0.1, quick: 2520 },
  { min: 144000, max: 300000, rate: 0.2, quick: 16920 },
  { min: 300000, max: 420000, rate: 0.25, quick: 31920 },
  { min: 420000, max: 660000, rate: 0.3, quick: 52920 },
  { min: 660000, max: 960000, rate: 0.35, quick: 85920 },
  { min: 960000, max: Infinity, rate: 0.45, quick: 181920 }
]

// 校验单个成员（姓名、关系、工资必填且工资>0）
function validateMember(member) {
  return member.name.trim() !== '' && 
         member.relation.trim() !== '' && 
         member.salary !== '' && !isNaN(member.salary)
}

// 校验所有成员，标记error状态
function validateAllMembers() {
  let isValid = true
  members.value.forEach(m => {
    const hasError = !validateMember(m)
    m.error = hasError
    if (hasError) isValid = false
  })
  return isValid
}

// 新增成员：先校验已有成员，通过后再添加
function addMember() {
  if (!validateAllMembers()) {
    ElMessage.error('请填写所有成员的必填项后再添加新成员')
    return
  }
  members.value.push({
    name: '',
    relation: '',
    salary: 0,
    labor: 0,
    copyright: 0,
    manuscript: 0,
    insurance: 0,
    error: false
  })
}

// 删除确认（Element Plus弹窗）
async function confirmRemoveMember(index) {
  const member = members.value[index]
  const name = member.name.trim() || '未命名成员'
  
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    removeMember(index)
    //提示删除成功
    ElMessage({message:"删除成功", type: 'success'})
  } catch (error) {
    // 取消删除，无操作
  }
}

// 删除成员（处理关联数据）
function removeMember(idx) {
  if (members.value.length > 1) {
    members.value.splice(idx, 1)
    // 清空专项附加扣除中指向被删成员的owner
    for (const key in deductionInfo.value) {
      if (Array.isArray(deductionInfo.value[key])) {
        // 处理数组形式的扣除项目
        deductionInfo.value[key].forEach(item => {
          if (item.owner && !members.value.some(m => m.name === item.owner)) {
            item.owner = ''
          }
        })
      } else {
        // 处理单个项目
        const owner = deductionInfo.value[key].owner
        if (owner && !members.value.some(m => m.name === owner)) {
          deductionInfo.value[key].owner = ''
        }
      }
    }
  }
}

function addElder() {
  deductionInfo.value.elder.push({ amount: 0, owner: '' })
}
function removeElder(idx) {
  if (deductionInfo.value.elder.length > 1) deductionInfo.value.elder.splice(idx, 1)
}
function checkElderLimit(idx) {
  if (deductionInfo.value.elder[idx].amount > 36000) {
    deductionInfo.value.elder[idx].amount = 36000
    ElMessage.warning('赡养老人单项不能超过36000元')
  }
}

// 子女教育/婴幼儿照护费相关函数
function addChild() {
  deductionInfo.value.child.push({ amount: 0, owner: '' })
}
function removeChild(idx) {
  if (deductionInfo.value.child.length > 1) deductionInfo.value.child.splice(idx, 1)
}
function checkChildLimit(idx) {
  if (deductionInfo.value.child[idx].amount > 24000) {
    deductionInfo.value.child[idx].amount = 24000
    ElMessage.warning('子女教育/婴幼儿照护费单项不能超过24000元')
  }
}

// 住房贷款利息相关函数
function addLoan() {
  deductionInfo.value.loan.push({ amount: 0, owner: '' })
}
function removeLoan(idx) {
  if (deductionInfo.value.loan.length > 1) deductionInfo.value.loan.splice(idx, 1)
}
function checkLoanLimit(idx) {
  if (deductionInfo.value.loan[idx].amount > 12000) {
    deductionInfo.value.loan[idx].amount = 12000
    ElMessage.warning('住房贷款利息单项不能超过12000元')
  }
}

// 住房租金相关函数
function addRent() {
  deductionInfo.value.rent.push({ amount: '', owner: '' })
}
function removeRent(idx) {
  if (deductionInfo.value.rent.length > 1) deductionInfo.value.rent.splice(idx, 1)
}

// 大病医疗相关函数
function addIllness() {
  deductionInfo.value.illness.push({ amount: 0, owner: '' })
}
function removeIllness(idx) {
  if (deductionInfo.value.illness.length > 1) deductionInfo.value.illness.splice(idx, 1)
}
function checkIllnessLimit(idx) {
  if (deductionInfo.value.illness[idx].amount > 65000) {
    deductionInfo.value.illness[idx].amount = 65000
    ElMessage.warning('大病医疗单项不能超过65000元')
  }
}

function addDegree() {
  deductionInfo.value.degree.push({ amount: 0, owner: '' })
}
function removeDegree(idx) {
  if (deductionInfo.value.degree.length > 1) deductionInfo.value.degree.splice(idx, 1)
}
function checkDegreeLimit(idx) {
  if (deductionInfo.value.degree[idx].amount > 4800) {
    deductionInfo.value.degree[idx].amount = 4800
    ElMessage.warning('学历继续教育单项不能超过4800元')
  }
}
function addEducation() {
  deductionInfo.value.education.push({ amount: 0, owner: '' })
}
function removeEducation(idx) {
  if (deductionInfo.value.education.length > 1) deductionInfo.value.education.splice(idx, 1)
}
function checkEducationLimit(idx) {
  if (deductionInfo.value.education[idx].amount > 3600) {
    deductionInfo.value.education[idx].amount = 3600
    ElMessage.warning('职业资格继续教育单项不能超过3600元')
  }
}

// 计算税额：先校验，通过后计算
async function calcTax() {
  if (!validateAllMembers()) {
    ElMessage.error('请填写所有成员的必填项')
    return
  }
  
  // 原有计算逻辑（略，保持原逻辑不变）
  const memberDeductions = {}
  for (const m of members.value) {
    memberDeductions[m.name] = {
      child: 0, loan: 0, rent: 0, illness: 0, elder: 0, education: 0, qualification: 0, degree: 0
    }
  }
  
  // 检查住房贷款利息和住房租金的冲突（同一人只能选择一项）
  const loanOwners = deductionInfo.value.loan.filter(item => item.owner).map(item => item.owner)
  const rentOwners = deductionInfo.value.rent.filter(item => item.owner).map(item => item.owner)
  
  for (const owner of loanOwners) {
    if (rentOwners.includes(owner)) {
      // 找到该人的贷款和租金项目
      const loanItems = deductionInfo.value.loan.filter(item => item.owner === owner)
      const rentItems = deductionInfo.value.rent.filter(item => item.owner === owner)
      
      // 计算总额
      const totalLoan = loanItems.reduce((sum, item) => sum + Number(item.amount || 0), 0)
      const totalRent = rentItems.reduce((sum, item) => sum + Number(item.amount || 0), 0)
      
      // 保留金额较高的项目，清空金额较低的项目
      if (totalLoan >= totalRent) {
        rentItems.forEach(item => item.owner = '')
      } else {
        loanItems.forEach(item => item.owner = '')
      }
    }
  }
  
  // 处理各项专项附加扣除
  for (const key in deductionInfo.value) {
    if (Array.isArray(deductionInfo.value[key])) {
      // 处理数组形式的扣除项目
      deductionInfo.value[key].forEach(({ amount, owner }) => {
        if (owner && memberDeductions[owner] !== undefined) {
          let max = 0
          if (key === 'child') max = 12 * 2000
          else if (key === 'loan') max = 12 * 1000
          else if (key === 'rent') max = 12 * 1500
          else if (key === 'illness') max = 80000 - 15000
          else if (key === 'elder') max = 12 * 3000
          else if (key === 'education') max = 3600
          else if (key === 'degree') max = 4800
          
          memberDeductions[owner][key] = (memberDeductions[owner][key] || 0) + Math.min(Number(amount || 0), max)
        }
      })
    } else {
      // 处理单个项目（保留字段）
      const { amount, owner } = deductionInfo.value[key]
      if (owner && memberDeductions[owner] !== undefined) {
        let max = 0
        if (key === 'qualification') max = 3600
        memberDeductions[owner][key] = Math.min(Number(amount || 0), max)
      }
    }
  }
  
  let res = []
  let total = 0
  for (let m of members.value) {
    let income = Number(m.salary) + Number(m.labor) * 0.8 + Number(m.copyright) * 0.8 + Number(m.manuscript) * 0.8 * 0.7
    let insurance = Number(m.insurance)
    let deduction = Object.values(memberDeductions[m.name]).reduce((a, b) => a + b, 0)
    let other = Number(otherDeduction.value)
    let fixed = 60000
    let taxable = income - fixed - insurance - deduction - other
    taxable = taxable < 0 ? 0 : taxable
    
    let rate = 0, quick = 0
    for (let t of taxTable) {
      if (taxable > t.min && taxable <= t.max) {
        rate = t.rate
        quick = t.quick
        break
      }
    }
    let tax = taxable * rate - quick
    tax = tax < 0 ? 0 : tax
    total += tax
    
    res.push({
      name: m.name,
      income,
      insurance,
      deduction,
      other,
      fixed,
      taxable,
      rate: rate * 100 + '%',
      quick,
      tax: tax.toFixed(2),
      deductions: { ...memberDeductions[m.name] }
    })
  }
  result.value = res
  totalTax.value = total.toFixed(2)
}

// 计算成员下拉选项
const memberOptions = computed(() => members.value.map(m => m.name.trim()).filter(Boolean))
// 修改为所有人都可以选择，不再限制特定关系
const elderOptions = computed(() => members.value.map(m => m.name.trim()).filter(Boolean))
const degreeOptions = computed(() => members.value.map(m => m.name.trim()).filter(Boolean))
const selfSpouseOptions = computed(() => members.value.map(m => m.name.trim()).filter(Boolean))
const educationOptions = computed(() => members.value.map(m => m.name.trim()).filter(Boolean))

// 计算专项项目下可选成员（防止同一专项重复选择同一人）
function getAvailableOwners(list, idx) {
  // 当前专项已被选中的成员（不含本项）
  const used = list.map((item, i) => i !== idx ? item.owner : null).filter(Boolean)
  return memberOptions.value.filter(name => !used.includes(name))
}

// 赡养老人
const elderAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.elder, idx)
// 子女教育/婴幼儿照护费
const childAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.child, idx)
// 住房贷款利息
const loanAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.loan, idx)
// 住房租金
const rentAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.rent, idx)
// 大病医疗
const illnessAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.illness, idx)
// 学历继续教育
const degreeAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.degree, idx)
// 职业资格继续教育
const educationAvailableOwners = (idx) => getAvailableOwners(deductionInfo.value.education, idx)

// 关系选项动态过滤
const relationAllOptions = [
  { value: '本人', label: '本人' },
  { value: '配偶', label: '配偶' },
  { value: '子女', label: '子女' },
  { value: '父亲', label: '父亲' },
  { value: '母亲', label: '母亲' },
  { value: '兄弟姐妹', label: '兄弟姐妹' },
  { value: '其他', label: '其他' },
]
function getRelationOptions(currentIdx) {
  const used = members.value.map((m, idx) => idx !== currentIdx ? m.relation : null)
  return relationAllOptions.filter(opt => {
    if(['本人','配偶','父亲','母亲'].includes(opt.value)) {
      return !used.includes(opt.value)
    }
    return true
  })
}

function generateTestMembers() {
  const relations = ['本人', '配偶', '子女', '父亲', '母亲', '兄弟姐妹', '其他']
  // 按照固定顺序生成4~7个成员
  const count = Math.floor(Math.random() * 4) + 4 // 4~7
  const arr = []
  for (let i = 0; i < count; i++) {
    arr.push({
      name: '测试' + relations[i],
      relation: relations[i],
      salary: Math.floor(Math.random() * 100000) + 10000,
      labor: Math.floor(Math.random() * 20000),
      copyright: Math.floor(Math.random() * 10000),
      manuscript: Math.floor(Math.random() * 5000),
      insurance: Math.floor(Math.random() * 20000),
      error: false
    })
  }
  members.value = arr
}
</script>

<style scoped>
/* 全局布局优化 */
.container {
  max-width: 1300px; 
  margin: 30px auto;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
  min-height: calc(100vh - 60px);
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.card {
  background: #fcfcfc;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 24px;
  margin-bottom: 24px;
}

/* 表格优化 */
.table-responsive {
  width: 100%;
  overflow-x: auto;
}

.table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}

.table th {
  background: #fafafa;
  font-weight: 600;
  color: #666;
}

.table th, .table td {
  border: 1px solid #eee;
  padding: 10px 8px;
  text-align: center;
  font-size: 14px;
  white-space: nowrap; 
}

/* 输入框和选择框优化 */
.input, select {
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 8px 10px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s;
  box-sizing: border-box;
}

.name-input {
  width: 100px; 
}

.relation-select {
  width: 110px; 
}

.input.short {
  width: 120px; 
}

.input:focus, select:focus {
  border-color: #42b983;
  box-shadow: 0 0 8px rgba(66,185,131,0.2);
}

/* 按钮优化 */
.btn {
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 8px;
}

.btn-primary {
  background: #42b983;
  color: #fff;
}

.btn-danger {
  background: #ff4d4f;
  color: #fff;
}

.btn-calc {
  background: #2f9e61;
  color: #fff;
  font-weight: 600;
}

.btn:hover {
  filter: brightness(90%);
}

.btn:active {
  transform: scale(0.98);
}

/* 专项附加扣除布局优化 */
.deduction-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  margin-top: 12px;
}

.deduction-group {
  display: contents;
}

.deduction-item {
  display: flex;
  align-items: center;
  min-width: 380px; 
  flex-wrap: nowrap; 
  margin-bottom: 8px;
}

/* 过渡动画样式 */
.deduction-item-enter-active,
.deduction-item-leave-active {
  transition: all 0.3s ease;
}

.deduction-item-enter-from {
  opacity: 0;
  transform: translateY(-20px);
  max-height: 0;
  margin-bottom: 0;
}

.deduction-item-leave-to {
  opacity: 0;
  transform: translateY(-20px);
  max-height: 0;
  margin-bottom: 0;
}

.deduction-item-move {
  transition: transform 0.3s ease;
}

.deduction-label {
  white-space: nowrap; 
  width: 140px; 
  text-align: right; 
  margin-right: 8px;
  color: #666;
}

.deduction-by {
  margin: 0 4px;
  color: #999;
}

.rent-group {
  position: relative;
}

.rent-tip {
  position: absolute;
  left: 0;
  top: 110%;
  background: #fffbe6;
  color: #b8860b;
  border: 1px solid #ffe58f;
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 10;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.tip {
  color: #888;
  font-size: 13px;
  margin: 8px 0;
}

.total-tax {
  font-size: 16px;
  color: #222;
  margin-top: 10px;
  font-weight: 600;
}

/* 移动端适配 */
.member-table-pc {
  display: block;
}

.member-cards-mobile {
  display: none;
}

.input-unit-group {
  display: flex;
  align-items: center;
}

.input-unit {
  margin-left: 4px;
  color: #888;
  font-size: 14px;
  white-space: nowrap;
}

.member-card {
  background: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
  padding: 12px;
  margin-bottom: 12px;
}

.member-card .row {
  margin-bottom: 8px;
}

.member-card .row label {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
  color: #333;
}

.member-card .row .input,
.member-card .row select {
  width: 100%;
}

@media (max-width: 768px) {
  .container {
    padding: 16px;
    margin: 16px auto;
  }
  
  .card {
    padding: 16px;
  }
  
  .member-table-pc {
    display: none;
  }
  
  .member-cards-mobile {
    display: block;
  }
  
  .member-card {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .member-card .row-pair {
    display: flex;
    gap: 8px;
    width: 100%;
  }
  
  .member-card .row-item {
    flex: 1;
  }
  
  .member-card .row-full {
    width: 100%;
  }
  
  .member-card .row label {
    font-size: 12px;
    margin-bottom: 2px;
  }
  
  .member-card .row .input,
  .member-card .row select {
    font-size: 12px;
    padding: 6px 8px;
  }
  
  /* 专项附加扣除：隐藏"元/年" + 缩小输入框/选择框 */
  .deduction-item {
    align-items: center;
    justify-content: flex-start;
    width: 100%;
    margin-bottom: 6px;
    min-width: 0;
    flex-wrap: nowrap;
    overflow: hidden;
  }
  .deduction-label {
    width: auto;
    min-width: 60px;
    max-width: 80px;
    margin-right: 4px;
    font-size: 12px;
    word-break: break-all;
    white-space: normal;
    display: flex;
    align-items: center;
    flex-shrink: 0;
  }
  .deduction-item button {
    vertical-align: middle;
    margin-right: 4px !important;
    margin-left: 0 !important;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }
  .deduction-item .input-unit-group,
  .deduction-item .input.short,
  .deduction-item select.short {
    margin-right: 2px;
    flex-shrink: 0;
  }
  .deduction-item .input.short,
  .deduction-item select.short {
    width: 60px;
    padding: 4px 4px;
    font-size: 12px;
  }
  .deduction-by {
    margin-left: auto;
    margin-right: 0;
    font-size: 12px;
    white-space: nowrap;
    flex-shrink: 0;
  }
}

@media (max-width: 576px) {
  .title {
    font-size: 20px;
  }
  
  .deduction-item {
    min-width: auto;
  }
}

/* 错误提示样式 */
.required {
  color: #ff4d4f;
  margin-left: 2px;
}

.input-error {
  border-color: #ff4d4f !important;
}

.error-tip {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 2px;
  height: 14px;
}
</style>